const { readFileSync } = require('fs')
const { resolve } = require('path')
const { compilerHtml } = require('./compiler')
const INNER = `<!-- inner -->`

class MdToHtmlPlugin {
    constructor({ template, filename }) {
        if (!template) throw new Error('template is missing')

        this.template = template
        this.filename = filename ? filename : 'md.html'
    }

    apply(compiler) {
        compiler.hooks.emit.tap('md-to-html-plugin', (compilation) => {
            const _assets = compilation.assets
            const _mdContent = readFileSync(this.template, 'utf8')
            const _templateHtml = readFileSync(resolve(__dirname, 'template.html'), 'utf8')
            const _mdContentArr = _mdContent.split('\n')
            const _htmlStr = compilerHtml(_mdContentArr)
            const _finalHtml = _templateHtml.replace(INNER, _htmlStr)
            _assets[this.filename] = {
                source() {
                    return _finalHtml
                },

                size() {
                    return _finalHtml.length
                }
            }
        })
    }
}

module.exports = MdToHtmlPlugin